package uk.co.javahelp.sender.message.csv;

import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import uk.co.javahelp.sender.message.Attachment;
import uk.co.javahelp.sender.message.Message;
import uk.co.javahelp.sender.message.MessageFactory;

public class CsvMessageFactory implements MessageFactory<String[]> {
	
	private static final String EMAIL = "email";
	
	private static final String CC = "cc";
	
	private final String today = new SimpleDateFormat("dd MMM yyyy").format(new Date());
	
    private final String template;
	
	private final Map<String, Integer> columns;
	
	private final Attachment[] attachments;
		
	public CsvMessageFactory(final String template, final Map<String, Integer> columns, final Attachment... attachments) {
		this.template = template;
		this.columns = columns;
		this.attachments = attachments;
	}

	@Override
	public Message createMessage(final String[] data) {
		final String to = data[this.columns.get(EMAIL)];
		final String cc = data[this.columns.get(CC)];
		final Message message = isEmpty(cc)
		    ? new Message(to, this.template)
	    	: new Message(to, cc, this.template);
		message.getAttachmentList().addAll(Arrays.asList(this.attachments));
		final Map<String, Object> attributes = message.getAttributes();
		for(final Map.Entry<String, Integer> column : this.columns.entrySet()) {
			attributes.put(column.getKey(), data[column.getValue()]);
			attributes.put("today", today);
		}
		return message;
	}
}
